{{/* Return the requested SVG icon */}}
{{/* Search for the icon in the Hugo Blox Builder icon library, falling back to user's icon library */}}

{{ $dirFile := path.Split .name }}
{{ $pack := .pack | default (strings.Replace $dirFile.Dir "/" "") | default "hero" }}
{{ $name := $dirFile.File }}

{{- $icon_pack := index site.Data.icons $pack -}}
{{- $icon := index (index $icon_pack "icons") $name -}}

{{ if $icon }}
  {{ if in (slice "hb" "brands") $pack }}
    {{/* Pass */}}
  {{ else }}
    {{ $icon_body := index $icon "body" }}
    {{ $icon_size := index $icon_pack "height" }}
    {{ $icon = printf `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %s %s">%s</svg>` (cast.ToString $icon_size) (cast.ToString $icon_size) $icon_body }}
  {{ end }}
{{ else }}
  {{ with index (index site.Data.icons.hb "icons") $name -}}
    {{ $icon = . }}
  {{ else }}
    {{ with resources.GetMatch (printf "media/icons/%s.svg" (path.Join $pack .name)) }}
      {{ $icon = .Content }}
    {{else}}
      {{ warnf "The icon `%s.svg` was not found in your `assets/media/icons/%s` folder" .name $pack }}
      {{ $icon = index (index site.Data.icons.brands "icons") "hugo" }}
    {{ end }}
  {{ end }}
{{ end }}

{{ if .attributes }}
  {{ $icon = replaceRE "<svg" (printf "<svg %s" .attributes) $icon }}
{{ end }}

{{- return ($icon | safeHTML) -}}
